package com.jims.master.modules.finance.service;

import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.RestUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.doctor.dao.ClinicOrdersCostDao;
import com.jims.master.modules.doctor.dao.ClinicOrdersDao;
import com.jims.master.modules.doctor.dao.PatVisitDao;
import com.jims.master.modules.doctor.dao.PatVisitIndexDao;
import com.jims.master.modules.doctor.entity.ClinicOrders;
import com.jims.master.modules.doctor.entity.ClinicOrdersCost;
import com.jims.master.modules.doctor.entity.PatVisit;
import com.jims.master.modules.doctor.entity.PatVisitIndex;
import com.jims.master.modules.doctor.vo.PrescDrugVo;
import com.jims.master.modules.finance.dao.InpBillDetailDao;
import com.jims.master.modules.finance.dao.InpSettleMasterDao;
import com.jims.master.modules.finance.dao.MedReceiptRecordMasterDao;
import com.jims.master.modules.finance.entity.InpBillDetail;
import com.jims.master.modules.finance.entity.MedReceiptRecordMaster;
import com.jims.master.modules.oper.dao.PriceListDao;
import com.jims.master.modules.sys.dao.ExternalUrlDao;
import com.jims.master.modules.sys.dao.OrgDeptDao;
import com.jims.master.modules.sys.dao.UserDao;
import com.jims.master.modules.sys.entity.ExternalUrl;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 医保
 * Created by zhangpeng on 2017/7/14.
 */
@Service
@Transactional(readOnly = true)
public class MedicalInsuranceService extends CrudService<ClinicOrdersCostDao, ClinicOrdersCost> {
    @Autowired
    private ClinicOrdersDao clinicOrdersDao;
    @Autowired
    private ClinicOrdersCostDao clinicOrdersCostDao;
    @Autowired
    private OutpRcptMasterService outpRcptMasterService;
    @Autowired
    private PriceListDao priceListDao;
    @Autowired
    private OrgDeptDao orgDeptDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private PatVisitDao patVisitDao;
    @Autowired
    private PatVisitIndexDao patVisitIndexDao;
    @Autowired
    private InpSettleMasterDao inpSettleMasterDao;
    @Autowired
    private InpBillDetailDao inpBillDetailDao;
    @Autowired
    private MedReceiptRecordMasterDao medReceiptRecordMasterDao;
    @Autowired
    private ExternalUrlDao externalUrlDao;

    /**
     * 医保住院-查询是否医保中心登记
     *
     * @param visitNo
     * @return
     */
    @Transactional
    public String findSickVisitInfo(String visitNo) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        PatVisit patVisitByVisitNo = patVisitDao.findPatVisitByVisitNo(visitNo, UserUtils.getOrgId());
        PatVisitIndex index = patVisitIndexDao.getInpPateientinfo(patVisitByVisitNo.getId());
        String residenceNo = index.getResidenceNo();
        if (StringUtils.isBlank(residenceNo)) {
            return "error";
        }
        params.put("residenceNo", residenceNo);//医保中心登记的住院号
        ExternalUrl url = externalUrlDao.getUrl(UserUtils.getOrgId(), "1");
        RestUtils<Map, HashMap> restUtils = new RestUtils<Map, HashMap>();
        Map<String, Object> resultList = restUtils.findById("/find/sickVisitInfo", Map.class, params, params, url.getUrl());
        if ("200".equals(resultList.get("statusCode"))) {
            Map mpa = (Map) resultList.get("body");
            /**
             * 医保住院状态 2001 已住院
             * 医保住院状态 2002 未住院
             */
            if ("2001".equals((String) mpa.get("result-code"))) {
                return "success";
            }
        }
        return "error";
    }

    /**
     * 医保结算主信息-调回门诊医保结算信息
     * PAY_TYPE：结算类型（1收费，2退费）默认收费
     * VISIT_NUMBER：处方号
     *
     * @param inParams
     * @return
     */
    @Transactional
    public String findRecordMaster(String inParams, String pay_type) {
        String[] orderIds = inParams.split(",");
        List list = new ArrayList();
        for (String orderId : orderIds) {
            List<BaseDto> clinicOrdersCostList = clinicOrdersCostDao.findCostList(orderId);
            for (int i = 0; i < clinicOrdersCostList.size(); i++) {
                String isUpload = clinicOrdersCostList.get(i).getAsString("isUpload");
                HashMap hashMap = new HashMap();
                if ("1".equals(isUpload)) {
                    hashMap.put("akc220", orderId.substring(orderId.length() - 10, orderId.length()));//处方号
                    hashMap.put("pay_type", StringUtils.isBlank(pay_type) ? "1" : pay_type);//默认收费
                }
                list.add(hashMap);
            }
        }
        if (list.size() == 0) {
            return null;
        }
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("visitNumber", list);//处方号 收费类型 集合
        ExternalUrl url = externalUrlDao.getUrl(UserUtils.getOrgId(), "1");
        RestUtils<Map, HashMap> restUtils = new RestUtils<Map, HashMap>();
        Map<String, Object> resultList = restUtils.findById("/receipt/recordMaster", Map.class, params, params, url.getUrl());
        if ("200".equals(resultList.get("statusCode"))) {
            Map mpa = (Map) resultList.get("body");
            ArrayList arrayList = (ArrayList) mpa.get("result-list");
            int insert = 0;
            Double pay_side1 = 0.00;//本次现金支付
            for (int i = 0; i < arrayList.size(); i++) {
                LinkedHashMap linkedHashMap = (LinkedHashMap) arrayList.get(i);
                MedReceiptRecordMaster medReceiptRecordMaster = toMedReceiptRecordMaster(linkedHashMap);
                String paySide1 = medReceiptRecordMaster.getPaySide1()== null ? "0" : medReceiptRecordMaster.getPaySide1();//本次现金支付
                pay_side1+=Double.valueOf(paySide1);
                insert += medReceiptRecordMasterDao.insert(medReceiptRecordMaster);
            }
            if (insert == arrayList.size()) {
                String str = "" + pay_side1;
                return str;
            }
        }
        return null;
    }

    MedReceiptRecordMaster toMedReceiptRecordMaster(LinkedHashMap linkedHashMap) {
        MedReceiptRecordMaster medReceiptRecordMaster = new MedReceiptRecordMaster();
        medReceiptRecordMaster.setHospitalNumber(linkedHashMap.get("hospital_number") == null ? "" : String.valueOf(linkedHashMap.get("hospital_number")));
        medReceiptRecordMaster.setChargeNumber(linkedHashMap.get("charge_number") == null ? "" : String.valueOf(linkedHashMap.get("charge_number")));
        medReceiptRecordMaster.setUnitNumber(linkedHashMap.get("unit_number") == null ? "" : String.valueOf(linkedHashMap.get("unit_number")));
        medReceiptRecordMaster.setPersonalNumber(linkedHashMap.get("personal_number") == null ? "" : String.valueOf(linkedHashMap.get("personal_number")));
        medReceiptRecordMaster.setName(linkedHashMap.get("name") == null ? "" : String.valueOf(linkedHashMap.get("name")));
        medReceiptRecordMaster.setSex(linkedHashMap.get("sex") == null ? "" : String.valueOf(linkedHashMap.get("sex")));
        String birth_date = linkedHashMap.get("birth_date") == null ? "" : String.valueOf(linkedHashMap.get("birth_date"));
        try {
            if (StringUtils.isNotBlank(birth_date)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Long aLong = Long.valueOf(birth_date);
                String S = dateFormat.format(aLong);
                Date parse = dateFormat.parse(S);
                medReceiptRecordMaster.setBirthDate(parse);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        medReceiptRecordMaster.setPersonalType(linkedHashMap.get("personal_type") == null ? "" : String.valueOf(linkedHashMap.get("personal_type")));
        medReceiptRecordMaster.setSickType(linkedHashMap.get("sick_type") == null ? "" : String.valueOf(linkedHashMap.get("sick_type")));
        medReceiptRecordMaster.setChargeSource(linkedHashMap.get("charge_source") == null ? "" : String.valueOf(linkedHashMap.get("charge_source")));
        medReceiptRecordMaster.setHospitalGrade(linkedHashMap.get("hospital_grade") == null ? "" : String.valueOf(linkedHashMap.get("hospital_grade")));
        medReceiptRecordMaster.setInCount(linkedHashMap.get("in_count") == null ? "" : String.valueOf(linkedHashMap.get("in_count")));
        String admission_date = linkedHashMap.get("admission_date") == null ? "" : String.valueOf(linkedHashMap.get("admission_date"));
        try {
            if (StringUtils.isNotBlank(admission_date)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Long aLong = Long.valueOf(admission_date);
                String S = dateFormat.format(aLong);
                Date parse = dateFormat.parse(S);
                medReceiptRecordMaster.setAdmissionDate(parse);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String discharge_date = linkedHashMap.get("discharge_date") == null ? "" : String.valueOf(linkedHashMap.get("discharge_date"));
        try {
            if (StringUtils.isNotBlank(discharge_date)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Long aLong = Long.valueOf(discharge_date);
                String S = dateFormat.format(aLong);
                Date parse = dateFormat.parse(S);
                medReceiptRecordMaster.setAdmissionDate(parse);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        medReceiptRecordMaster.setDiagnosisName(linkedHashMap.get("diagnosis_name") == null ? "" : String.valueOf(linkedHashMap.get("diagnosis_name")));
        medReceiptRecordMaster.setResidenceNo(linkedHashMap.get("residence_no") == null ? "" : String.valueOf(linkedHashMap.get("residence_no")));
        medReceiptRecordMaster.setTotalCost(linkedHashMap.get("total_cost") == null ? "" : String.valueOf(linkedHashMap.get("total_cost")));
        medReceiptRecordMaster.setPayWave(linkedHashMap.get("pay_wave") == null ? "" : String.valueOf(linkedHashMap.get("pay_wave")));
        medReceiptRecordMaster.setPaySide1(linkedHashMap.get("pay_side1") == null ? "" : String.valueOf(linkedHashMap.get("pay_side1")));
        medReceiptRecordMaster.setPaySide2(linkedHashMap.get("pay_side2") == null ? "" : String.valueOf(linkedHashMap.get("pay_side2")));
        medReceiptRecordMaster.setPaySide3(linkedHashMap.get("pay_side3") == null ? "" : String.valueOf(linkedHashMap.get("pay_side3")));
        medReceiptRecordMaster.setPaySide4(linkedHashMap.get("pay_side4") == null ? "" : String.valueOf(linkedHashMap.get("pay_side4")));
        medReceiptRecordMaster.setPaySide5(linkedHashMap.get("pay_side5") == null ? "" : String.valueOf(linkedHashMap.get("pay_side5")));
        medReceiptRecordMaster.setPaySide6(linkedHashMap.get("pay_side6") == null ? "" : String.valueOf(linkedHashMap.get("pay_side6")));
        medReceiptRecordMaster.setPaySide7(linkedHashMap.get("pay_side7") == null ? "" : String.valueOf(linkedHashMap.get("pay_side7")));
        medReceiptRecordMaster.setPaySide8(linkedHashMap.get("pay_side8") == null ? "" : String.valueOf(linkedHashMap.get("pay_side8")));
        medReceiptRecordMaster.setVisitNumber(linkedHashMap.get("visit_number") == null ? "" : String.valueOf(linkedHashMap.get("visit_number")));
        medReceiptRecordMaster.setTakeFlag(linkedHashMap.get("take_flag") == null ? "" : String.valueOf(linkedHashMap.get("take_flag")));
        String handle_date = linkedHashMap.get("handle_date") == null ? "" : String.valueOf(linkedHashMap.get("handle_date"));
        try {
            if (StringUtils.isNotBlank(handle_date)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Long aLong = Long.valueOf(handle_date);
                String S = dateFormat.format(aLong);
                Date parse = dateFormat.parse(S);
                medReceiptRecordMaster.setAdmissionDate(parse);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        medReceiptRecordMaster.setPayType(linkedHashMap.get("pay_type") == null ? "" : String.valueOf(linkedHashMap.get("pay_type")));
        medReceiptRecordMaster.setOperator(linkedHashMap.get("operator") == null ? "" : String.valueOf(linkedHashMap.get("operator")));
        medReceiptRecordMaster.setCkb002(linkedHashMap.get("ckb002") == null ? "" : String.valueOf(linkedHashMap.get("ckb002")));
        medReceiptRecordMaster.setCkb006(linkedHashMap.get("ckb006") == null ? "" : String.valueOf(linkedHashMap.get("ckb006")));
        medReceiptRecordMaster.setCkb012(linkedHashMap.get("ckb012") == null ? "" : String.valueOf(linkedHashMap.get("ckb012")));
        return medReceiptRecordMaster;
    }

    /**
     * 医保结算主信息-调回住院医保结算信息
     * @param visitNo
     * @return
     */
    @Transactional
    public String findRecordMasterInp(String visitNo) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        PatVisit patVisitByVisitNo = patVisitDao.findPatVisitByVisitNo(visitNo, UserUtils.getOrgId());
        PatVisitIndex index = patVisitIndexDao.getInpPateientinfo(patVisitByVisitNo.getId());
        String residenceNo = index.getResidenceNo();
        if (StringUtils.isBlank(residenceNo)) {
            return "error";
        }
        params.put("residenceNo", residenceNo);
        ExternalUrl url = externalUrlDao.getUrl(UserUtils.getOrgId(), "1");
        RestUtils<Map, HashMap> restUtils = new RestUtils<Map, HashMap>();
        Map<String, Object> resultList = restUtils.findById("/receipt/recordMasterInp", Map.class, params, params, url.getUrl());
        if ("200".equals(resultList.get("statusCode"))) {
            Map mpa = (Map) resultList.get("body");
            ArrayList arrayList = (ArrayList) mpa.get("result-list");
            int insert = 0;
            Double pay_side3 = 0.00;
            Double pay_side4 = 0.00;
            Double pay_side5 = 0.00;
            Double pay_side6 = 0.00;
            Double CKB002 = 0.00;
            Double CKB006 = 0.00;
            Double CKB012 = 0.00;
            Double costAll = 0.00; //报销总费用
            Double pay_side1 = 0.00;//本次现金支付
            for (int i = 0; i < arrayList.size(); i++) {
                LinkedHashMap linkedHashMap = (LinkedHashMap) arrayList.get(i);
                MedReceiptRecordMaster medReceiptRecordMaster = toMedReceiptRecordMaster(linkedHashMap);
                String paySide1 = medReceiptRecordMaster.getPaySide1();//本次现金支付
                pay_side1+=Double.valueOf(paySide1);
                String paySide3 = medReceiptRecordMaster.getPaySide3();//本次统筹应支付金额
                pay_side3 += Double.valueOf(paySide3);
                String paySide4 = medReceiptRecordMaster.getPaySide4();//本次大病基金支付金额
                pay_side4 += Double.valueOf(paySide4);
                String paySide5 = medReceiptRecordMaster.getPaySide5();//本次补充基金支付金额
                pay_side5 += Double.valueOf(paySide5);
                String paySide6 = medReceiptRecordMaster.getPaySide6();//本次公务员津贴支付金额
                pay_side6 += Double.valueOf(paySide6);
                String ckb002 = medReceiptRecordMaster.getCkb002();//救助新增支出
                CKB002 += Double.valueOf(ckb002);
                String ckb006 = medReceiptRecordMaster.getCkb006();//贫困救助支出
                CKB006 += Double.valueOf(ckb006);
                String ckb012 = medReceiptRecordMaster.getCkb012();//学生二次补偿
                CKB012 += Double.valueOf(ckb012);
                insert += medReceiptRecordMasterDao.insert(medReceiptRecordMaster);
            }
            if (insert == arrayList.size()) {
                costAll = pay_side3 + pay_side4+ pay_side5 +pay_side6+ CKB002+ CKB006+ CKB012;
                String str = "" + costAll;
                return str;
            }
        }
        return null;
    }

    /**
     * 住院医保撤回
     *
     * @param visitNo
     * @return
     */
    @Transactional
    public String medicalInsurRefund(String visitNo) {
        PatVisit patVisit = patVisitDao.findPatVisitByVisitNo(visitNo, UserUtils.getOrgId());
        PatVisitIndex patVisitIndex = patVisitIndexDao.getInpPateientinfo(patVisit.getId());
        if (patVisitIndex==null || StringUtils.isBlank(patVisitIndex.getResidenceNo())) {
            return "error";
        }
        InpBillDetail inpBillDetail = new InpBillDetail();
        inpBillDetail.setOrgId(UserUtils.getOrgId());
        inpBillDetail.setPatVisit(patVisit);
        List<BaseDto> baseDtoList = inpBillDetailDao.findBillDetailList(inpBillDetail);
        if(baseDtoList==null) return "error";
        Iterator<BaseDto> iteratorList = baseDtoList.iterator();
        while (iteratorList.hasNext()) {
            BaseDto baseDto = iteratorList.next();
            String isUpload = baseDto.getAsString("isUpload");
            if ("0".equals(isUpload) || StringUtils.isBlank(isUpload)) {
                iteratorList.remove();
            }
        }
        int i =0;
        for (BaseDto BaseDto : baseDtoList) {
            InpBillDetail InpBillDetail = new InpBillDetail();
            Object id = BaseDto.get("id");
            InpBillDetail.setId(String.valueOf(id));
            InpBillDetail.setIsUpload("0");//医保是否上传 1上传 0未上传
            i+=inpBillDetailDao.updtateIsUpload(InpBillDetail);
        }
        if(i==baseDtoList.size()){
            return "success";
        }
        return "error";
    }

    /**
     * 医保报销-住院数据上传
     */
    @Transactional(readOnly = false)
    public String saveKC27(String visitNo) {
        PatVisit patVisit = patVisitDao.findPatVisitByVisitNo(visitNo, UserUtils.getOrgId());
        PatVisitIndex patVisitIndex = patVisitIndexDao.getInpPateientinfo(patVisit.getId());
        if (patVisitIndex==null || StringUtils.isBlank(patVisitIndex.getResidenceNo())) {
            return "error";
        }
        String residenceNo = patVisitIndex.getResidenceNo();
        InpBillDetail inpBillDetail = new InpBillDetail();
        inpBillDetail.setOrgId(UserUtils.getOrgId());
        inpBillDetail.setPatVisit(patVisit);
        List<BaseDto> baseDtoList = inpBillDetailDao.findBillDetailList(inpBillDetail);
        if(baseDtoList==null) return "error";
        Iterator<BaseDto> iteratorList = baseDtoList.iterator();
        while (iteratorList.hasNext()) {
            BaseDto baseDto = iteratorList.next();
            String isUpload = baseDto.getAsString("isUpload");
            if ("1".equals(isUpload)) {
                iteratorList.remove();
            }
        }
        long along = System.currentTimeMillis();
        for (int i = 0; i < baseDtoList.size(); i++) {
            BaseDto baseDto = baseDtoList.get(i);
            baseDto = toBaseDto(baseDto);
            Long aLong = along + i;
            String serialNo = aLong.toString();// 结算号
            baseDto.put("AKB020", "67"); //医疗机构编号 医疗机构在医保中心登记的编号（此编号必需与医保中心登记的一致，否则影响结算）
            baseDto.put("CKC179", residenceNo);//住院号  医保结算系统录入的结算号
            baseDto.put("AKC190", " ");//结算号  给空值（由医保产生）
            baseDto.put("CKC158", serialNo.substring(serialNo.length() - 6, serialNo.length())); //费用项目序号 HIS产生
        }
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("inpBillDetailList", baseDtoList);
        RestUtils<Map, HashMap> restUtils = new RestUtils<Map, HashMap>();
        ExternalUrl url = externalUrlDao.getUrl(UserUtils.getOrgId(), "1");
        Map<String, Object> resultList = new HashMap<>();
        resultList = restUtils.findById("/KC27/saveVisit", Map.class, params, params, url.getUrl());
        if ("200".equals(resultList.get("statusCode"))) {
            Map mpa = (Map) resultList.get("body");
            if ("添加成功".equals((String) mpa.get("result-code"))) {
                for (BaseDto BaseDto : baseDtoList) {
                    InpBillDetail InpBillDetail = new InpBillDetail();
                    Object id = BaseDto.get("id");
                    InpBillDetail.setId(String.valueOf(id));
                    Object ckc158 = BaseDto.get("CKC158");
                    InpBillDetail.setRcptNo(String.valueOf(ckc158));
                    InpBillDetail.setIsUpload("1");//医保是否上传 1上传 0未上传
                    inpBillDetailDao.updtateIsUpload(InpBillDetail);
                }
                return "success";
            }
        }
        return "error";
    }

    BaseDto toBaseDto(BaseDto baseDto) {
        InpBillDetail InpBillDetail = inpBillDetailDao.get(String.valueOf(baseDto.get("id")));
        //AKC220 处方号 HIS产生
        baseDto.put("AAE011", userDao.getInfoById(InpBillDetail.getCreateBy().getId()).getName());//经办人	明细录入操作员
        baseDto.put("AAE036", InpBillDetail.getCreateDate()); // 经办日期	明细录入操作时间
        String itemClass = baseDto.getAsString("aka063");//AKA063 收费项目类别	与医保目录项目类别必须一致，参见指标项定义 附表1
        String itemCode = baseDto.getAsString("AKC222");//AKC222 收费项目代码	HIS定义
        if ("C".equals(itemClass)) {
            baseDto.put("AKA063", "D");
            baseDto.put("CKE081", "D");
        } else if ("D".equals(itemClass)) {
            baseDto.put("AKA063", "E");
            baseDto.put("CKE081", "E");
        } else if ("E".equals(itemClass)) {
            baseDto.put("AKA063", "F");
            baseDto.put("CKE081", "F");
        } else if ("F".equals(itemClass) || "Z".equals(itemClass) || "M".equals(itemClass)) {
            baseDto.put("AKA063", "G");
            baseDto.put("CKE081", "G");
        } else if ("G".equals(itemClass)) {
            baseDto.put("AKA063", "Z");
            baseDto.put("CKE081", "Z");
        } else if ("H".equals(itemClass)) {
            baseDto.put("AKA063", "N");
            baseDto.put("CKE081", "N");
        } else if ("I".equals(itemClass)) {
            baseDto.put("AKA063", "U");
            baseDto.put("CKE081", "U");
        } else if ("L".equals(itemClass)) {
            baseDto.put("AKA063", "O");
            baseDto.put("CKE081", "O");
        } else if ("K".equals(itemClass)) {
            baseDto.put("AKA063", "T");
            baseDto.put("CKE081", "T");
        } else if ("K".equals(itemClass)) {
            baseDto.put("AKA063", "T");
            baseDto.put("CKE081", "T");
        } else if ("B".equals(itemClass)) {
            baseDto.put("AKA063", "C");
            baseDto.put("CKE081", "C");
        } else if ("A".equals(itemClass) && "B".equals(itemCode.substring(0, 1))) {
            baseDto.put("AKA063", "B");
            baseDto.put("CKE081", "B");
        } else {
            baseDto.put("AKA063", "A");
            baseDto.put("CKE081", "A");
        }
        if (!"A".equals(itemClass) || !"B".equals(itemClass)) {
            baseDto.put("CKC160", "/"); // 单位
        } else {
            String units = baseDto.getAsString("ckc160");
            baseDto.put("CKC160", outpRcptMasterService.getViemCode(units).getAsString("itemname")); // 单位
        }
        //AKC223 收费项目名称	HIS定义
        //AKC227 金额	单价*数量后四舍五入保留两位小数
        //CKC197 单价	不能小于等于0，最多四位小数
        //CKC198 数量	不能等于0
        //CKC159 规格	汉字，诊疗项目以“/”代替
        //CKC160 计价单位	代码 ，与医保计价单位一致，参考视图 “VIEW_CODE”
        //CKC161 与中心对应关系	医保收费项目的代码（视图PARA_CAPTURE_ITEM的ITEM_CODE）
        baseDto.put("CKC169", orgDeptDao.get(InpBillDetail.getPerformDept()).getDeptName());//执行科室名称	汉字
        baseDto.put("CKC170", userDao.getInfoById(InpBillDetail.getOrderDoctor()).getName());//开方医生	汉字
        baseDto.put("CKC171", orgDeptDao.get(InpBillDetail.getOrderDept()).getDeptName());//开方科室名称	汉字
        //CKE081 收据项目分类	参见指标项定义 附表1
        //CKE085 对应科室核算项目	参见指标项定义 附表1
        //CKE086 对应会计科目	参见指标项定义 附表1
        //CKE089 换算比例	默认1
        //CKE090 出院带药标志	默认“在院用药”
        //SKA003 是否医保项目	001是  000否
        return baseDto;
    }


    /**
     * 医保报销-门诊处方数据上传
     */
    @Transactional(readOnly = false)
    public String saveYibaoServer(String inParams, String clinicNo) {
        String[] orderIds = inParams.split(",");
        Map<String, Object> map2 = new HashMap<>();
        List<BaseDto> clinicOrdersCostListAll = new ArrayList<>();
        long along = System.currentTimeMillis();
        HashMap<String, Object> params = new HashMap<String, Object>();
        int jvalue = 0;
        for (int j = 0;j< orderIds.length ; j++) {
            String orderId = orderIds[j];
            ClinicOrders clinicOrders = clinicOrdersDao.get(orderId);
            List<BaseDto> clinicOrdersCostList = clinicOrdersCostDao.findCostList(orderId);
            for (int i = 0; i < clinicOrdersCostList.size(); i++) {
                clinicOrdersCostList.get(i).put("AKC220", orderId.substring(orderId.length() - 10, orderId.length()));
                Long aLong= along + i+ jvalue;
                String serialNo = aLong.toString();// 结算号
                clinicOrdersCostList.get(i).put("CKC158", serialNo.substring(serialNo.length() - 6, serialNo.length()));
                clinicOrdersCostList.get(i).put("AKB020", "67");
                clinicOrdersCostList.get(i).put("CKC170", userDao.getInfoById(clinicOrders.getCreateBy().getId()).getName());//开方医生
                clinicOrdersCostList.get(i).put("AAE011", userDao.getInfoById(UserUtils.getUser().getId()).getName());//经办人
                String implementdept = orgDeptDao.get(clinicOrders.getImplementDept()).getDeptName();// 执行科室
                clinicOrdersCostList.get(i).put("CKC169", implementdept);
                String applyDept = orgDeptDao.get(clinicOrders.getApplyDept()).getDeptName();//开单科室
                clinicOrdersCostList.get(i).put("CKC171", applyDept);
                String itemClass = clinicOrdersCostList.get(i).getAsString("aka063");
                String itemCode = clinicOrdersCostList.get(i).getAsString("AKC222");
                if ("C".equals(itemClass)) {
                    clinicOrdersCostList.get(i).put("AKA063", "D");
                    clinicOrdersCostList.get(i).put("CKE081", "D");
                } else if ("D".equals(itemClass)) {
                    clinicOrdersCostList.get(i).put("AKA063", "E");
                    clinicOrdersCostList.get(i).put("CKE081", "E");
                } else if ("E".equals(itemClass)) {
                    clinicOrdersCostList.get(i).put("AKA063", "F");
                    clinicOrdersCostList.get(i).put("CKE081", "F");
                } else if ("F".equals(itemClass) || "Z".equals(itemClass) || "M".equals(itemClass)) {
                    clinicOrdersCostList.get(i).put("AKA063", "G");
                    clinicOrdersCostList.get(i).put("CKE081", "G");
                } else if ("G".equals(itemClass)) {
                    clinicOrdersCostList.get(i).put("AKA063", "Z");
                    clinicOrdersCostList.get(i).put("CKE081", "Z");
                } else if ("H".equals(itemClass)) {
                    clinicOrdersCostList.get(i).put("AKA063", "N");
                    clinicOrdersCostList.get(i).put("CKE081", "N");
                } else if ("I".equals(itemClass)) {
                    clinicOrdersCostList.get(i).put("AKA063", "U");
                    clinicOrdersCostList.get(i).put("CKE081", "U");
                } else if ("L".equals(itemClass)) {
                    clinicOrdersCostList.get(i).put("AKA063", "O");
                    clinicOrdersCostList.get(i).put("CKE081", "O");
                } else if ("K".equals(itemClass)) {
                    clinicOrdersCostList.get(i).put("AKA063", "T");
                    clinicOrdersCostList.get(i).put("CKE081", "T");
                } else if ("K".equals(itemClass)) {
                    clinicOrdersCostList.get(i).put("AKA063", "T");
                    clinicOrdersCostList.get(i).put("CKE081", "T");
                } else if ("B".equals(itemClass)) {
                    clinicOrdersCostList.get(i).put("AKA063", "C");
                    clinicOrdersCostList.get(i).put("CKE081", "C");
                } else if ("A".equals(itemClass) && "B".equals(itemCode.substring(0, 1))) {
                    clinicOrdersCostList.get(i).put("AKA063", "B");
                    clinicOrdersCostList.get(i).put("CKE081", "B");
                } else {
                    clinicOrdersCostList.get(i).put("AKA063", "A");
                    clinicOrdersCostList.get(i).put("CKE081", "A");
                }
                if (!"A".equals(itemClass) || !"B".equals(itemClass)) {
                    clinicOrdersCostList.get(i).put("CKC160", "/"); // 单位
                } else {
                    String units = clinicOrdersCostList.get(i).getAsString("ckc160");
                    clinicOrdersCostList.get(i).put("CKC160", outpRcptMasterService.getViemCode(units).getAsString("itemname")); // 单位
                }
//                clinicOrdersCostList.get(i).put("AKC227",clinicOrdersCostList.get(i).getAsString("charges")); // 金额
//                clinicOrdersCostList.get(i).put("CKC197",clinicOrdersCostList.get(i).getAsString("price")); // 单价
//                clinicOrdersCostList.get(i).put("CKC198",clinicOrdersCostList.get(i).getAsString("num")); // 数量
//                clinicOrdersCostList.get(i).put("CKC227",clinicOrdersCostList.get(i).getAsString("spec")); // 规格
                clinicOrdersCostList.get(i).put("AAE036", clinicOrders.getCreateDate()); // 时间
            }
            jvalue += clinicOrdersCostList.size();
            clinicOrdersCostListAll.addAll(clinicOrdersCostList);
        }
        params.put("clinicOrdersCostList", clinicOrdersCostListAll);
        ExternalUrl url = externalUrlDao.getUrl(UserUtils.getOrgId(), "1");
        RestUtils<Map, HashMap> restUtils = new RestUtils<Map, HashMap>();
        map2 = restUtils.findById("/KC28/saveOutp", Map.class, params, params, url.getUrl());
        if ("200".equals(map2.get("statusCode"))) {
            Map mpa = (Map) map2.get("body");
            if ("添加成功".equals((String) mpa.get("result-code"))) {
                for (BaseDto baseDto : clinicOrdersCostListAll) {
                    String id = (String) baseDto.get("id");
                    ClinicOrdersCost clinicOrdersCost = new ClinicOrdersCost();
                    clinicOrdersCost.setId(id);
                    clinicOrdersCost.setIsUpload("1");//医保是否上传 1上传 0未上传
                    clinicOrdersCostDao.updtateIsUpload(clinicOrdersCost);
                }
                Long serialNo = along;
                return serialNo.toString();
            } else {
                return null;
            }
        } else {
            return null;
        }

    }

    /**
     * test-结算主记录防重复插入
     * 有待完善--慎用
     * @param personalNumber
     * @return
     */
    @Transactional
    public String testInsertSelect(String personalNumber) {
        MedReceiptRecordMaster medReceiptRecordMaster = medReceiptRecordMasterDao.get(personalNumber);
        int insert = medReceiptRecordMasterDao.insertSelect(medReceiptRecordMaster);
        if (insert == 1) {
            String str = "" + insert;
            return str;
        }
        return null;
    }

    public static void main(String[] args) {
        long along = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            Long aLong = along + i;
            String serialNo = aLong.toString();// 结算号
            System.out.println(serialNo.substring(serialNo.length() - 6, serialNo.length()));
        }
        for (int i = 0; i < 100; i++) {
            Random rd = new Random(); // 创建随机对象
            String n = "";
            int rdGet; // 取得随机数
            do {
                rdGet = Math.abs(rd.nextInt()) % 10 + 48; // 产生48到57的随机数(0-9的键位值)
                char num1 = (char) rdGet;
                String dd = Character.toString(num1);
                n += dd;
            } while (n.length() < 6);// 假如长度小于4
            System.out.println(n + i);
        }
    }
}
